<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="消息提示的文案" type="info">
      </el-alert>
      <!-- 步骤条区 -->
      <el-steps :space="200" :active="activeName-0" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="d商品参数"></el-step>
        <el-step title="j商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>

      </el-steps>
      <!-- 表单验证，结构 -->
      <el-form :model="addForm" :rules="addFormRules" ref="raddFormRef">
        <!-- table栏切换 -->
        <el-tabs @tab-click="handleCateClick" :before-leave="beforeLeave" v-model="activeName" tab-position="left">
          <!-- 1.基本信息 -->
          <el-tab-pane label="基本信息" name='0'>
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <!-- 级联 -->
              <el-cascader @change="handleChange" clearable v-model="addForm.goods_cat" :options="cateList"
                :props="{ expandTrigger: 'hover',label:'cat_name',value:'cat_id'}"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 2.动态参数 -->
          <el-tab-pane label="动态参数" name='1'>
            <!-- 渲染动态参数表格 -->
            <el-form-item v-for="item in manyTabData" :key="item.attr_id" :label="item.attr_name">
              <br>
              <!-- checkbox多选框渲染 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="item1" v-for="(item1,index1) in item.attr_vals1" :key="index1">
                </el-checkbox>

              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 3.静态属性 -->
          <el-tab-pane label="静态参数" name='2'>
            <el-form-item :label="item.attr_name" v-for="item in onlyTabData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 4.商品内容 -->
          <el-tab-pane label="商品图片" name='3'>
            <!-- upload组件 -->
            <el-upload :on-success="handleSuccess" :headers="headersObj" class="upload-demo"
              action='http://42.192.71.221:8889/api/private/v1/upload' :on-preview="handlePreview"
              :on-remove="handleRemove" :file-list="fileList" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <!-- 富文本编辑器 -->
          <el-tab-pane label="商品内容" name='4'>
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- <br> -->
            <!-- 添加商品按钮 -->
            <el-button type="primary" class="btnAdd" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 弹出图片对话框 -->
    <el-dialog :visible.sync="previewImgDialog" width="50%">
      <img :src="imgUrl" style="width:100%">
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
export default {
  data () {
    return {
      // content : '',
      imgUrl: '',
      // 弹出框显示隐藏
      previewImgDialog: false,
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      fileList: [],
      onlyTabData: [],
      manyTabData: [],
      cateList: [],
      activeName: '0',
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [1, 3, 6],
        pics: [],
        goods_introduce: ''
      },
      addFormRules: {
        goods_name: [{ required: true, message: '请输入正确的商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入正确的商品价格', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入正确的商品数量', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入正确的商品名重量', trigger: 'blur' }]
      }

    }
  },
  methods: {
    // 添加商品，发送ajax请求
    addGoods () {
      // console.log('添加商品')
      this.$refs.raddFormRef.validate(async bool => {
        if (!bool) return this.$message.error('请填写必填项')
        const form = cloneDeep(this.addForm)
        console.log(form)
        // 修改goods_cat数据格式
        form.goods_cat = form.goods_cat.join(',')
        // 循环动态参数
        form.attrs = []
        this.manyTabData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
          })
        })
        // 循环静态属性
        this.onlyTabData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })
        // console.log(form)
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error('创建商品失败')
        this.$message.success('创建成功')
        // console.log(res)
        // 返回缓存上级路由
        this.$router.go(-1)
      })
    },
    // 触发上传事件函数 response是响应回来的数据
    handleSuccess (response) {
      // console.log(response)
      this.addForm.pics.push({
        pic: response.data.tmp_path
      })
      console.log(this.addForm)
    },
    // 图片预览效果
    handlePreview ({ response: { data } }) {
      // console.log(file)
      this.imgUrl = 'http://42.192.71.221:8889/' + data.tmp_path
      this.previewImgDialog = true
    },
    // 商品图片删除时触发
    handleRemove (file) {
      const i = this.addForm.pics.findIndex(item => item.pic === file.response.data.tmp_path)
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm)
    },
    async handleCateClick () {
      if (this.activeName === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
        if (res.meta.status !== 200) return this.$message.error('添加失败')
        res.data.forEach(item => {
          item.attr_vals1 = item.attr_vals = item.attr_vals.split(' ')
        })
        this.manyTabData = res.data
        // console.log(this.manyTabData)
      } else if (this.activeName === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
        if (res.meta.status !== 200) return this.$message.error('添加失败')

        this.onlyTabData = res.data
        console.log(this.onlyTabData)
      }
    },
    // tabs跳转的钩子属性 to 去那个 from 来自哪个
    beforeLeave (to, from) {
      if (from === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择分类信息')
        return false
      }
      // console.log(to, from)
    },
    // 级联选择器触发事件
    handleChange () {
      // console.log(this.addForm.goods_cat)
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
        return true
      }
    },
    // 获取商品信息
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      this.cateList = res.data
      // console.log(this.cateList)
    }
  },
  computed: {
    cateId () {
      return this.addForm.goods_cat[2]
    }
  },
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getCateList()
  },
  mounted () { }
}
</script>
<style scoped lang='less'>
.el-steps {
  margin: 15px;
}
/deep/ .el-step__title {
  font-size: 12px;
}
/deep/ .ql-editor {
  height: 240px;
  // margin-bottom: 15px;
}
.btnAdd {
  margin-top: 15px;
}
</style>
